﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WcfServer.Classes.Utility;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Security.Cryptography;

namespace WcfServer.Classes.Client
{
    [Serializable]
    public class DirectInitiator
    {
        public string SenderUserID { set; get; }
        public string SenderIPAddress { set; get; }
        public DateTime TimeStamp { set; get; }
        public byte[] SessionKey { set; get; }
       // public byte[] MessageSign { set; get; }//TODO: ADD SIGN!


        public static string GetPublicIP()
        {
            String direction = "";
            WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
            using (WebResponse response = request.GetResponse())
                using (StreamReader stream = new StreamReader(response.GetResponseStream()))
                {
                    direction = stream.ReadToEnd();
                }

            //Search for the ip in the html
            int first = direction.IndexOf("Address: ") + 9;
            int last = direction.LastIndexOf("</body>");
            direction = direction.Substring(first, last - first);

            return direction;
        }

        public DirectInitiator(String UserName)
        {
            SenderUserID = UserName;
            SenderIPAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork).ToString();
            //GetPublicIP();
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            aes.KeySize = 128;
            aes.GenerateKey();
            SessionKey = aes.Key; // key should be kept somewhere in RAM.
            TimeStamp = DateTime.Now;
        }

        public DirectInitiator(byte[] data, String ContainerName)
        {
            byte[] temp = EncryptionHandler.DecryptRSA(data,ContainerName);
            var di = SerializerHandler<DirectInitiator>.DeSerializeInput(temp);
            this.SenderIPAddress = di.SenderIPAddress;
           // this.MessageSign = di.MessageSign;
            this.SenderUserID = di.SenderUserID;
            this.SessionKey = di.SessionKey;
            this.TimeStamp = di.TimeStamp;
        }
        public byte[] Send(String XmlPub)
        {
            var di = SerializerHandler<DirectInitiator>.SerializeInput(this);
            return EncryptionHandler.EncryptRSA_XML(di,XmlPub);
        }
    }
}
